package com.hlkj.warboot.module_sys.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hlkj.warboot.configurer.util.LoggerUtil;
import com.hlkj.warboot.configurer.util.ResponseUtil;
import com.hlkj.warboot.configurer.util.StrUtil;
import com.hlkj.warboot.configurer.util.base.BaseExceptionUtil;
import com.hlkj.warboot.module_sys.entity.PermissionEntity;
import com.hlkj.warboot.module_sys.entity.RoleEntity;
import com.hlkj.warboot.module_sys.entity.wrapper.RoleWrapper;
import com.hlkj.warboot.module_sys.mapper.PermissionMapper;
import com.hlkj.warboot.module_sys.mapper.RoleMapper;
import com.hlkj.warboot.module_sys.service.RoleService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 系统角色 前端控制器
 * </p>
 *
 * @author lixing_java@163.com
 * @since 2020-06-11
 */
@Controller
@RequestMapping("/sys/role")
public class RoleControler {
    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleService roleService;

    @Resource
    private PermissionMapper permissionMapper;

    /*
     * @Description TODO 分页
     * @Author 李星
     * @Date 2019/2/16 13:08
     * @Param []
     * @return org.springframework.web.servlet.ModelAndView
     */
    @GetMapping("toPage")
    public ModelAndView toPage() throws Exception {
        return new ModelAndView("sys/role/roleList");
    }

    @PostMapping("page")
    @ResponseBody
    public Object page(RoleEntity entity) throws Exception {
        LoggerUtil.info(MessageFormat.format("【角色分页】条件：{0}", JSON.toJSONString(entity)));

        IPage<RoleEntity> iPage = roleService.page(new Page<>(entity.basePageNum, entity.basePageSize), RoleWrapper.queryWrapper(entity));

        LoggerUtil.info(MessageFormat.format("【角色分页】结果：{0}", iPage.getSize()));
        return ResponseUtil.success(iPage);
    }

    /*
     * @Description TODO 跳转到角色编辑页面
     * @Author 李星
     * @Date 2019/9/10 13:57
     * @Param [category, id]
     * @return org.springframework.web.servlet.ModelAndView
     */
    @GetMapping("toModify/{id}")
    public ModelAndView toModify(@PathVariable String id) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        if ("null".equals(id)) {
            modelAndView.setViewName("sys/role/roleAdd");
        } else {
            modelAndView.setViewName("sys/role/roleUpdate");
            RoleEntity roleEntity = roleService.getById(id); // 查询角色信息
            modelAndView.addObject("entity", roleEntity);
        }
        return modelAndView;
    }

    /*
     * @Description TODO 角色编辑保存
     * @Author 李星
     * @Date 2019/9/10 16:12
     * @Param [entity]
     * @return java.lang.Object
     */
    @PostMapping("saveModify/{category}")
    @ResponseBody
    public Object saveModify(RoleEntity entity, @PathVariable String category) throws Exception {
        boolean flag;
        if ("insert".equals(category)) {
            flag = roleService.save(entity); // 添加保存
        } else if ("update".equals(category)) {
            flag = roleService.updateById(entity); // 编辑保存
        } else {
            throw new BaseExceptionUtil("保存编辑角色页面时获取参数失败");
        }
        if (flag) {
            return ResponseUtil.success();
        } else {
            return ResponseUtil.fail("操作失败");
        }
    }

    /*
     * @Description TODO 删除角色
     * @Author 李星
     * @Date 2019/9/11 9:14
     * @Param [entity]
     * @return java.lang.Object
     */
    @PostMapping("delete")
    @ResponseBody
    public Object delete(RoleEntity entity) throws Exception {
        LoggerUtil.info(MessageFormat.format("【角色删除】条件：{0}", entity.getId()));

        // TODO 角色表和角色-权限中间表做了主外键关联，所以删除角色或权限会级联删除中间表中的数据
        boolean flag;
        if (StrUtil.isEffective(entity.getId())) {
            if (entity.getId().contains(",")) {
                flag = roleService.removeByIds(Arrays.asList(entity.getId().split(",")));
            } else {
                flag = roleService.removeById(entity.getId());
            }
            LoggerUtil.info(MessageFormat.format("【角色删除】结果：{0}", flag));
            return ResponseUtil.success(flag);
        } else {
            return ResponseUtil.fail("主键缺失");
        }
    }

    /*
     * @Description TODO 跳转到角色授权页面
     * @Author 李星
     * @Date 2019/9/12 16:34
     * @Param [roleId 待授权的角色编号]
     * @return java.lang.Object
     */
    @RequestMapping("toAuthorization/{roleId}")
    public Object toAuthorization(@PathVariable String roleId) throws Exception {
        ModelAndView modelAndView = new ModelAndView("sys/role/roleAuthorization");

        PermissionEntity permissionEntity = new PermissionEntity();
        permissionEntity.setBaseAdminRoleId(roleId); // 角色编号
        permissionEntity.setActive(1); // 权限状态（1:有效,2:禁用）
        List<PermissionEntity> permissionEntityList = permissionMapper.selectCasRole(permissionEntity);

        modelAndView.addObject("roleId", roleId);
        modelAndView.addObject("permissionList", permissionEntityList);
        return modelAndView;
    }

    /*
     * @Description TODO 角色授权
     * @Author 李星
     * @Date 2019/9/12 16:34
     * @Param [id]
     * @return java.lang.Object
     */
    @RequestMapping("authorization")
    @ResponseBody
    public Object authorization(RoleEntity entity) throws Exception {
        LoggerUtil.info(MessageFormat.format("【角色授权】条件：{0}", JSONObject.toJSONString(entity)));

        int deleteResult = roleMapper.deleteRolePermission(entity);
        LoggerUtil.info(MessageFormat.format("【清空角色（{0}）的所有权限】结果：{1}", entity.getId(), deleteResult));

        if (StrUtil.isEffective(entity.getBaseAdminPermissionId())) {
            entity.setBaseList(Arrays.asList(entity.getBaseAdminPermissionId().split(","))); // 权限编号集合
            entity.setBaseAdminPermissionId(null);
            int insertResult = roleMapper.insertRolePermission(entity); // 批量添加权限数据
            LoggerUtil.info(MessageFormat.format("【批量添加角色（{0}）的权限】结果：{1}", entity.getId(), insertResult));
        }

        return ResponseUtil.success();
    }

}

